#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    //修改标题
    this->setWindowTitle("我的记事本");
    //创建菜单栏
    QMenuBar* menubar = menuBar();
    //创建菜单
    QMenu* menu1 = new QMenu("文件");
    menubar->addMenu(menu1);
    //创建菜单项
    QAction* action1 = new QAction("保存");
    QAction* action2 = new QAction("加载");
    //将菜单项添加到菜单中
    menu1->addAction(action1);
    menu1->addAction(action2);
    //创建一个edit用来存储数据
    edit = new QTextEdit(this);
    this->setCentralWidget(edit);
    edit->setPlaceholderText("请在这里输入");
    //将保存和加载两个行为关联槽函数
    connect(action1,&QAction::trigger,this,&MainWindow::save);
    connect(action1,&QAction::trigger,this,&MainWindow::load);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::save()
{
    //进行文件的保存
    //弹出对话框，选择文件路径
    QFileDialog* dialog = new QFileDialog(this);
    QString filename = dialog->getSaveFileName(this,"保存文件","D:/");
    qDebug() << "filename: " << filename;
    //打开文件
    std::ofstream file(filename.toStdString().c_str());
    if(!file.is_open())
    {
        qDebug() << "打开文件失败";
        file.close();
        return;
    }
    //获得到中央控件的内容
    const QString& text = edit->toPlainText();
    //写入到文件中
    file << text;
    file.close();
}

void MainWindow::load()
{
    //弹出对话框，选择打开的文件
    QFileDialog* dialog = new QFileDialog(this);
    QString filename = dialog->getOpenFileName(this,"加载文件","D:/");
    qDebug() << "filename: " << filename;
    //打开文件
    std::ifstream file(filename.toStdString().c_str());
    if(!file.is_open())
    {
        qDebug() << "加载文件失败" << endl;
        file.close();
        return;
    }
    //向文件中写入
    std::string context,str;
    while(getline(file,str))
    {
        context += str;
        context += "\n";
    }
    //把context写入到edit中
    QString text = QString::fromStdString(context);
    edit->setPlainText(text);
    //关闭文件
    file.close();
}

